package cn.com.hongfu.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import cn.com.hongfu.model.User;
import cn.com.hongfu.service.UserService;
import cn.com.hongfu.utils.Utils;
@Controller
@RequestMapping("/login")
public class LoginController {
	@Autowired
	public UserService userService ;
	public static final String USERID = "userId";
	public static final String USERNAME ="userName";
	/**
	 * 返回登录视图
	 * @return
	 */
	@RequestMapping("/loginUI")
	public String UI(HttpSession session){
		String result = "/login/login";
		if(session.getAttribute(this.USERID)!=null)
			result = "redirect:/login/login.html" ;
		return result;
	}
	/**
	 * 登录处理
	 * @param user
	 * @param modelMap
	 * @return 根据验证结果返回不同的视图
	 */
	@RequestMapping("/login")
	public String login(User user,ModelMap modelMap,HttpServletRequest request,HttpSession httpSession){
		String url = "/login/loginfail";
		if(httpSession.getAttribute(this.USERID)!=null){
			return "redirect:/main/index.html" ;
		}
		try {
			user.setPassword(Utils.encrypt(user.getPassword()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		User u = userService.login(user);
		if(u != null){
			httpSession.setAttribute(this.USERID, u.getId());
			httpSession.setAttribute(this.USERNAME, u.getUsername());
			url = "redirect:/main/index.html" ; 
		}
		return url;
	}
	@RequestMapping("/otherHandUI")
	public String otherHandUI(){
		return "/login/other";
	}
	@RequestMapping("/logout")
	public String logout(HttpSession httpSession){
		httpSession.removeAttribute(USERID);
		httpSession.removeAttribute(USERNAME);
		return "redirect:/index/index.html" ;
	}
	
}
